namespace Yaaf.Wp7.AdvancedExplorer
{
    using System;
    using System.IO;
    using System.IO.IsolatedStorage;

    public class Logger
    {
        private readonly string fileToLog;

        private static Logger logger = null;

        /// <summary>
        /// A static ViewModel used by the views to bind against.
        /// </summary>
        /// <returns>The MainViewModel object.</returns>
        public static Logger Instance
        {
            get
            {
                // Delay creation of the view model until necessary
                if (logger == null)
                {
                    logger = new Logger("logfile.log");
                }

                return logger;
            }

            set
            {
                logger = value;
            }
        }

        public Logger(string fileToLog)
        {
            this.fileToLog = fileToLog;
        }

        private string last = "";

        public void WriteLine(string format, params object[] data)
        {
            var line = string.Format(format, data);
            var currentWrite = string.Format("\n\n{0:s}: {1}", DateTime.Now, line);
            last += currentWrite;
            try
            {
                var storage = IsolatedStorageFile.GetUserStoreForApplication();
                using (var stream = storage.OpenFile(this.fileToLog, FileMode.Append, FileAccess.Write))
                using (var writer = new StreamWriter(stream))
                {
                    writer.Write(last);
                }
                
                last = "";
            }
            catch (IsolatedStorageException)
            {
            }
            catch(System.Text.EncoderFallbackException e)
            {
                //TODO Check when this Exception happens and howto handle (Catched due debugging purposes)
                //try
                //{
                //    var storage = IsolatedStorageFile.GetUserStoreForApplication();
                //    storage.DeleteFile(this.fileToLog);
                //}
                //catch (IsolatedStorageException)
                //{
                //}
            }
        }

    }

}